package cn.lg.soar.database.handler.type;

import cn.lg.soar.common.util.data.StringUtil;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;
import org.apache.ibatis.type.TypeHandler;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * List<Integer> 类型处理器
 * @author luguoxiang
 * @date 2022-05-20
 * 开源项目：https://gitee.com/lgx1992/lg-soar 求star！请给我star！请帮我点个star！
 */
@MappedJdbcTypes(JdbcType.VARCHAR)
@MappedTypes(List.class)
public class IntListTypeHandler implements TypeHandler<List<Integer>> {
    @Override
    public void setParameter(PreparedStatement preparedStatement, int i, List<Integer> longs, JdbcType jdbcType) throws SQLException {
        preparedStatement.setString(i, StringUtil.toString(longs));
    }

    @Override
    public List<Integer> getResult(ResultSet resultSet, String s) throws SQLException {
        String vs = resultSet.getString(s);
        if (vs == null) {
            return null;
        }
        if (StringUtil.isBlank(vs)) {
            return Collections.emptyList();
        }
        return Arrays.stream(vs.split(StringUtil.COMMA)).map(Integer::parseInt)
                .collect(Collectors.toList());
    }

    @Override
    public List<Integer> getResult(ResultSet resultSet, int i) throws SQLException {
        String vs = resultSet.getString(i);
        if (vs == null) {
            return null;
        }
        if (StringUtil.isBlank(vs)) {
            return Collections.emptyList();
        }
        return Arrays.stream(vs.split(StringUtil.COMMA)).map(Integer::parseInt)
                .collect(Collectors.toList());
    }

    @Override
    public List<Integer> getResult(CallableStatement callableStatement, int i) throws SQLException {
        String vs = callableStatement.getString(i);
        if (vs == null) {
            return null;
        }
        if (StringUtil.isBlank(vs)) {
            return Collections.emptyList();
        }
        return Arrays.stream(vs.split(StringUtil.COMMA)).map(Integer::parseInt)
                .collect(Collectors.toList());
    }

}
